package com.ts.proj.json;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.AuthConstant;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.entity.excelEntity.SystemUserExcelEntity;
import com.ts.proj.service.SystemUserService;
import com.ts.util.DateUtil;
import com.ts.util.EasyPoiUtil;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class SystemUserJson extends BaseController {

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 用户管理--用户列表-数据格式
     * @param start
     * @param length
     * @return
     */
    @RequestMapping("/user-list-json/{start}/{length}")
    public Map<String,Object> userListJson(@PathVariable("start") Integer start, @PathVariable("length") Integer length){
        PageData pageData = this.getPageData();
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        Integer roleId = 0;
        try{
            roleId = Integer.valueOf(pageData.get("key").toString());
        }catch (Exception e){

        }
        if(pageData.get("from")!=null&&!"".equals(pageData.get("from").toString())){
            param.put("minCreateTime", pageData.get("from").toString() + " 00:00:00");
        }
        if(pageData.get("to")!=null&&!"".equals(pageData.get("to").toString())){
            param.put("maxCreateTime", pageData.get("to").toString() + " 23:59:59");
        }
        if(null!=pageData.get("belongTo")&&!"".equals(pageData.getString("belongTo"))){
            param.put("belongTo", pageData.getString("belongTo"));
        }
        if(null!=pageData.get("powerLevel")&&!"".equals(pageData.getString("powerLevel"))){
            param.put("powerLevel", pageData.getString("powerLevel"));
        }
        if(0!=roleId){
            param.put("roleId",roleId);
        }
        List<SystemUserEntity> systemUserEntities = systemUserService.findAll(param,start==0?0:start-1,length);
        Long count = systemUserService.count(param);
        pageData.put("total", count);
        pageData.put("rows", systemUserEntities);
        return pageData;
    }

   
    @RequestMapping("/user-ins-upd-del/{id}")
    public String userOperation(@PathVariable("id") String id){
        Integer idInteger = Integer.valueOf(id);
        SystemUserEntity systemUserEntity = systemUserService.findById(idInteger);
        PageData pd = this.getPageData();
        if(null!=pd.get("username")&&!"".equals(pd.getString("username"))){
            systemUserEntity.setUsername(pd.getString("username"));
        }
        if(null!=pd.get("password")&&!"".equals(pd.getString("password"))){
            systemUserEntity.setPassword(new Md5Hash(pd.getString("password"), systemUserEntity.getUsername() + AuthConstant.DEFAULTSALT).toString());
            systemUserEntity.setSalt(AuthConstant.DEFAULTSALT);
        }
        if(null!=pd.get("nickname")&&!"".equals(pd.getString("nickname"))){
            systemUserEntity.setNickname(pd.getString("nickname"));
        }
        if(null!=pd.get("role_id")&&!"".equals(pd.getString("role_id"))){
            systemUserEntity.setRoleId(Integer.valueOf(pd.getString("role_id")));
        }
        if(null!=pd.get("group_id")&&!"".equals(pd.getString("group_id"))){
            systemUserEntity.setBelongTo(pd.getString("group_id"));
        }
        if(null!=pd.get("power_level")&&!"".equals(pd.getString("power_level"))){
            systemUserEntity.setPowerLevel(pd.getString("power_level"));
        }
        if(null!=pd.get("delete_flag")&&!"".equals(pd.getString("delete_flag"))){
            systemUserEntity.setDeleteFlag(InsUpdDelFlagConstant.DELETE_FLAG_Y);
        }
        if(null!=pd.get("locked")&&!"".equals(pd.getString("locked"))){
            systemUserEntity.setLocked(systemUserEntity.getLocked()?false:true);
        }
        //表示清理缓存
        if(null!=pd.get("flag")&&!"".equals(pd.getString("flag"))){
            //删除所有就的session
            this.getRequest().getSession().removeAttribute(ConsoleConstant.SESSIONUSER);
            this.getRequest().getSession().removeAttribute(ConsoleConstant.RIGHTS);
            this.getRequest().getSession().removeAttribute(ConsoleConstant.ROLEID);
            this.getRequest().getSession().removeAttribute(ConsoleConstant.BUTTONRIGHTS);
        }
        Iterator shortCutIterable = pd.keySet().iterator();
        List<String> idsList = new ArrayList<>();
        while (shortCutIterable.hasNext()) {
            String shortCut = shortCutIterable.next().toString();
            if (shortCut.startsWith("checkBoxName_")) {
                String ids = shortCut.split("_")[1];
                idsList.add(ids);
            }
        }
        try {
            String shortCode = "S"+String.valueOf(RightsHelper.sumRights(idsList.toArray(new String[idsList.size()])));
            systemUserEntity.setUserShortCut(shortCode);
        } catch (Exception e) {

        }
        SystemUserEntity systemUsersEntity = systemUserService.save(systemUserEntity);

        return "success";

    }

    @RequestMapping("/user-ins-upd-del/batch/{id}")
    public String userBatchOpertion(@PathVariable("id") String id){
        PageData pd = this.getPageData();
        String [] ids = id.split("@");
        List<SystemUserEntity> list = new ArrayList<>();
        for(String str :ids){
            SystemUserEntity systemUserEntity = systemUserService.findById(Integer.valueOf(str));
            if(null!=pd.get("locked")&&!"".equals(pd.getString("locked"))){
                boolean pre = systemUserEntity.getLocked();
                systemUserEntity.setLocked(!pre);
                list.add(systemUserEntity);
            }
        }
        systemUserService.saveAll(list);
        return "success";
    }

    @RequestMapping("/user-check/{username}")
    public String userCheck(@PathVariable("username") String username){
        PageData pd = new PageData();
        pd.put("username", username);
        List<SystemUserEntity> all = systemUserService.findAll(pd);
        //表示新增

        if(0==all.size()){
            return "success";
        }
        return "error";
    }

    @RequestMapping("/user-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemUserEntity> systemUserEntities = systemUserService.findAll(param);
        List<SystemUserExcelEntity> systemUserExcelEntities = new ArrayList<>();
        for(SystemUserEntity systemUserEntity :systemUserEntities){
            SystemUserExcelEntity entity = new SystemUserExcelEntity();
            entity.setUsername(systemUserEntity.getUsername());
            entity.setBelongTo(systemUserEntity.getBelongTo());
            entity.setNickname(systemUserEntity.getNickname());
            entity.setPowerLevel(systemUserEntity.getPowerLevel());
            entity.setRoleId(systemUserEntity.getRoleId());
            systemUserExcelEntities.add(entity);
        }
        EasyPoiUtil.exportExcel(systemUserExcelEntities,"","",SystemUserExcelEntity.class, DateUtil.getID()+".xls",response);
    }

}
